package com.xushi.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class SmsUtil {
    public static Integer appid;
    public static String appkey;
    public static Integer templateId;
    public static String nationCode;
    public static String sign;

    @Value("${tencent.sms.appid}")
    public void setAppid(Integer appid) {
        SmsUtil.appid = appid;
    }
    @Value("${tencent.sms.appkey}")
    public void setAppkey(String appkey) {
        SmsUtil.appkey = appkey;
    }
    @Value("${tencent.sms.templateid}")
    public void setTemplateId(Integer templateId) {
        SmsUtil.templateId = templateId;
    }
    @Value("${tencent.sms.nationCode}")
    public void setNationCode(String nationCode) {
        SmsUtil.nationCode = nationCode;
    }
    @Value("${tencent.sms.sign}")
    public void setSign(String sign) {
        SmsUtil.sign = sign;
    }

    private static final String singleSmsUrl = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";
    private static final String multiSmsUrl = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2";

    public static Map<String, Object> sendSms(String phoneNumber, String verificationCode) {
        ArrayList<String> params = new ArrayList<>();
        params.add(verificationCode);
        params.add("5");

        Map<String, Object> resultMap = new HashMap<>();
        try {
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,
                    templateId, params, sign, "", "");
            resultMap.put("code", 1);
            resultMap.put("message", "send successfully");
            return resultMap;
        } catch (HTTPException e) {
            // HTTP响应码错误
            resultMap.put("message", e);
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            resultMap.put("message", e);
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            resultMap.put("message", e);
            e.printStackTrace();
        }
        resultMap.put("code", 2);
        return resultMap;
    }

    public static String generateVerificationCode() {
        Random r = new Random(System.currentTimeMillis());
        int code = (int) (r.nextDouble() * 1000_000);
        return String.valueOf(code);
    }
}
